/**
 * API配置统一管理
 *
 * 功能特性：
 * - 统一API基础URL配置
 * - 环境变量支持
 * - 超时和重试配置
 * - 错误处理配置
 *
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

// API配置接口
export interface ApiConfig {
  baseURL: string;
  timeout: number;
  retryCount: number;
  retryDelay: number;
}

// 环境配置映射
const ENV_CONFIGS: Record<string, ApiConfig> = {
  development: {
    baseURL: process.env.REACT_APP_API_URL || 'http://localhost:6001',
    timeout: 15000,
    retryCount: 3,
    retryDelay: 1000,
  },
  production: {
    baseURL: process.env.REACT_APP_API_URL || 'https://api.example.com',
    timeout: 10000,
    retryCount: 2,
    retryDelay: 2000,
  },
  test: {
    baseURL: process.env.REACT_APP_API_URL || 'https://test-api.example.com',
    timeout: 30000,
    retryCount: 1,
    retryDelay: 500,
  },
};

// 获取当前环境
const getCurrentEnvironment = (): string => {
  return process.env.NODE_ENV || 'development';
};

// 导出API配置
export const API_CONFIG: ApiConfig = ENV_CONFIGS[getCurrentEnvironment()];

// 导出环境信息
export const API_ENV = {
  current: getCurrentEnvironment(),
  isDevelopment: getCurrentEnvironment() === 'development',
  isProduction: getCurrentEnvironment() === 'production',
  isTest: getCurrentEnvironment() === 'test',
};

// API端点配置
export const API_ENDPOINTS = {
  // 智能体管理
  agents: {
    list: '/api/app/agent',
    create: '/api/app/agent',
    update: (id: string) => `/api/app/agent/${id}`,
    delete: (id: string) => `/api/app/agent/${id}`,
    start: (id: string) => `/api/app/agent/${id}/start`,
    stop: (id: string) => `/api/app/agent/${id}/stop`,
    restart: (id: string) => `/api/app/agent/${id}/restart`,
    test: (id: string) => `/api/app/agent/${id}/test`,
    stats: (id: string) => `/api/app/agent/${id}/stats`,
  },

  // 模型配置
  modelConfigs: {
    list: '/api/app/model-config',
    create: '/api/app/model-config',
    update: (id: string) => `/api/app/model-config/${id}`,
    delete: (id: string) => `/api/app/model-config/${id}`,
    test: (id: string) => `/api/app/model-config/${id}/test`,
  },

  // 提示词模板
  promptTemplates: {
    list: '/api/app/prompt-template',
    create: '/api/app/prompt-template',
    update: (id: string) => `/api/app/prompt-template/${id}`,
    delete: (id: string) => `/api/app/prompt-template/${id}`,
  },

  // 对话管理
  conversations: {
    list: '/api/app/conversation',
    create: '/api/app/conversation',
    update: (id: string) => `/api/app/conversation/${id}`,
    delete: (id: string) => `/api/app/conversation/${id}`,
    messages: (id: string) => `/api/app/conversation/${id}/messages`,
    sendMessage: (id: string) => `/api/app/conversation/${id}/messages`,
  },

  // 用户认证
  auth: {
    login: '/api/auth/login',
    register: '/api/auth/register',
    logout: '/api/auth/logout',
    refresh: '/api/auth/refresh-token',
    profile: '/api/auth/me',
    changePassword: '/api/auth/change-password',
    forgotPassword: '/api/auth/forgot-password',
    resetPassword: '/api/auth/reset-password',
  },

  // MCP服务器
  mcpServers: {
    list: '/api/app/mcp-server',
    create: '/api/app/mcp-server',
    update: (id: string) => `/api/app/mcp-server/${id}`,
    delete: (id: string) => `/api/app/mcp-server/${id}`,
    test: (id: string) => `/api/app/mcp-server/${id}/test-connection`,
  },

  // MCP工具
  mcpTools: {
    list: '/api/app/mcp-tool',
    create: '/api/app/mcp-tool',
    update: (id: string) => `/api/app/mcp-tool/${id}`,
    delete: (id: string) => `/api/app/mcp-tool/${id}`,
    execute: (id: string) => `/api/app/mcp-tool/${id}/execute`,
  },

  // 系统监控
  monitoring: {
    health: '/api/app/monitoring/health',
    metrics: '/api/app/monitoring/metrics',
    logs: '/api/app/monitoring/logs',
  },
};

// 默认请求配置
export const DEFAULT_REQUEST_CONFIG = {
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
};

// 错误消息映射
export const ERROR_MESSAGES = {
  NETWORK_ERROR: '网络连接失败，请检查网络设置',
  TIMEOUT_ERROR: '请求超时，请稍后重试',
  AUTH_ERROR: '认证失败，请重新登录',
  PERMISSION_ERROR: '权限不足，无法访问此资源',
  NOT_FOUND: '请求的资源不存在',
  SERVER_ERROR: '服务器内部错误，请稍后重试',
  VALIDATION_ERROR: '请求数据验证失败',
  UNKNOWN_ERROR: '未知错误，请稍后重试',
};

// HTTP状态码映射
export const STATUS_CODE_MAP = {
  200: '成功',
  201: '创建成功',
  204: '删除成功',
  400: '请求错误',
  401: '未授权',
  403: '禁止访问',
  404: '资源不存在',
  422: '验证错误',
  500: '服务器错误',
  502: '网关错误',
  503: '服务不可用',
};

// 导出工具函数
export const apiUtils = {
  // 构建完整URL
  buildUrl: (endpoint: string): string => {
    return `${API_CONFIG.baseURL}${endpoint}`;
  },

  // 获取错误消息
  getErrorMessage: (error: any): string => {
    if (!error.response) {
      return ERROR_MESSAGES.NETWORK_ERROR;
    }

    const status = error.response.status;
    if (STATUS_CODE_MAP[status as keyof typeof STATUS_CODE_MAP]) {
      return STATUS_CODE_MAP[status as keyof typeof STATUS_CODE_MAP];
    }

    return ERROR_MESSAGES.UNKNOWN_ERROR;
  },

  // 检查是否为网络错误
  isNetworkError: (error: any): boolean => {
    return !error.response && error.message === 'Network Error';
  },

  // 检查是否为超时错误
  isTimeoutError: (error: any): boolean => {
    return error.code === 'ECONNABORTED' && error.message.includes('timeout');
  },

  // 检查是否为认证错误
  isAuthError: (error: any): boolean => {
    return error.response?.status === 401;
  },

  // 格式化查询参数
  formatQueryParams: (params: Record<string, any>): string => {
    const searchParams = new URLSearchParams();

    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    return searchParams.toString();
  },
};

export default API_CONFIG;